import 'dart:io';

import 'package:dio/dio.dart';
import 'package:erp/constant.dart';
import 'package:erp/data/http/Result.dart';
import 'package:erp/main_state.dart';
import 'package:erp/routes/app_pages.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart' hide Response;

/// 业务请求拦截器
class RequestInterceptor extends InterceptorsWrapper {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (options.extra.containsKey("needTip") && options.extra["needTip"] == true) {
      EasyLoading.show(status: "加载中...");
    }

    MainState ms = Get.find<MainState>();
    if (ms.token.value != null) {
      options.headers[R.TOKEN_HEADER_NAME] = ms.token.value!.token;
    }
    return handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) async {
    if (response.requestOptions.extra.containsKey("needTip") && response.requestOptions.extra["needTip"] == true) {
      await Future.delayed(Duration(milliseconds: 500));
      EasyLoading.dismiss();
    }

    if (response.data is Map) {
      Map<String, dynamic> _data = response.data;
      Result result = Result.fromJson(_data);
      if (result.code == 500) {
        await Future.delayed(Duration(milliseconds: 800));
        EasyLoading.showError(result.msg ?? '服务异常');
        return handler.reject(DioError(
          requestOptions: response.requestOptions,
          response: response,
          type: DioErrorType.response,
          error: result.toJson(),
        ));
      }

      /// 直接取出data属性
      response.data = result.data;
      return handler.resolve(response);
    }
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) async {
    if (err.requestOptions.extra.containsKey("needTip") && err.requestOptions.extra["needTip"] == true) {
      await Future.delayed(Duration(milliseconds: 500));
      EasyLoading.dismiss();
    }

    /// other
    if (err.error is SocketException) {
      SocketException exception = err.error;
      OSError osError = exception.osError!;
      EasyLoading.showInfo("${osError.message}");
    }

    if (err.type == DioErrorType.connectTimeout) {
      EasyLoading.showInfo("请求超时");
    }

    /// 这里说明服务器返回响应了
    if (err.type == DioErrorType.response && err.response != null) {
      Response response = err.response!;
      EasyLoading.showInfo("${response.data["msg"]},即将退出登陆！", duration: Duration(seconds: 3));
      Future.delayed(Duration(seconds: 3), () => {Get.offAllNamed(Routes.LOGIN), Get.find<MainState>().clearAuth()});
    }
    return handler.next(err);
  }
}
